//
//  CPGlobalFunc.swift
//  cockpit
//
//  Created by Haijun Si on 2020/7/7.
//  Copyright © 2020 chenganrt. All rights reserved.
//

import UIKit

// MARK: - 全局window
public func keyWindow() -> UIWindow? {
    var keyWindow:UIWindow? = nil
    if #available(iOS 13.0, *) {
        for windowScene:UIWindowScene in (UIApplication.shared.connectedScenes as? Set<UIWindowScene>)! {
            if windowScene.activationState == .foregroundActive {
                keyWindow = windowScene.windows.last
            }
            break
        }
    }
    else {
        keyWindow = UIApplication.shared.keyWindow
    }
    return keyWindow
}

/// 显示加载框
///
/// - Parameter touchOutSideRemove: 是否触摸外部消失
public func showLoading(touchOutSideRemove : Bool = false){
    DispatchQueue.main.async {
        ToastAgent.shared.beginLogin(touchOutSideRemove: touchOutSideRemove)
    }
}

/// 隐藏加载框
public func hideLoading(){
    DispatchQueue.main.async {
        ToastAgent.shared.hide()
    }
}

/// 显示提示文字
///
/// - Parameter text: 文字信息
public func toast(text:String){
    DispatchQueue.main.async {
        ToastAgent.shared.showText(text: text)
    }
}

public func toast(text:String, showTime:TimeInterval){
    DispatchQueue.main.async {
        ToastAgent.shared.showText(text: text,interval:showTime )
    }
}


/**
 获取当前视图的控制器
 
 @return 控制器
 */
func CP_getCurrentViewController() -> UIViewController {
    var currentViewController = CP_getRootViewController();
    while true {
        if (currentViewController.presentedViewController) != nil {
            currentViewController = currentViewController.presentedViewController!;
        } else if currentViewController is UINavigationController {
            let navigationController = currentViewController as! UINavigationController;
            currentViewController = navigationController.children.last!;
        }
        else if currentViewController is UITabBarController {
            let tabBarController = currentViewController as! UITabBarController;
            currentViewController = tabBarController.selectedViewController!;
        }
        else {
            let childViewControllerCount = currentViewController.children.count;
            if childViewControllerCount > 0 {
                currentViewController = currentViewController.children.last!;
                return currentViewController;
            } else {
                return currentViewController;
            }
        }
    }
    return currentViewController;
}

func CP_getRootViewController() -> UIViewController {
    let window = UIApplication.shared.delegate?.window as? UIWindow
    return window!.rootViewController!
}

// MARK: - 全局alertview
func showAlertViewMethodAndCallBack(title:String?, message: String?, showType:UIAlertController.Style? = .alert, cancelTitle:String?, cancelBtnCallBack: (((UIAlertAction) -> Void)? ), doneTitle:String?, doneBtnCallBack: (((UIAlertAction) -> Void)?)) {
       
    let alert = UIAlertController.init(title: title ?? "提示", message: message ?? "", preferredStyle: showType ?? .alert)
    
    if cancelTitle != nil {
        let cancelAction = UIAlertAction.init(title: cancelTitle ?? "", style: UIAlertAction.Style.default, handler: cancelBtnCallBack)
         alert.addAction(cancelAction)
    }
    
    if doneTitle != nil {
        let doneAction = UIAlertAction.init(title: doneTitle ?? "", style: UIAlertAction.Style.default, handler: doneBtnCallBack)
        alert.addAction(doneAction)
    }
    
    let cancel = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel, handler: nil)
       
    alert.addAction(cancel)
    CP_getCurrentViewController().present(alert, animated: true, completion: nil)
}


//func userIsLogin(isToLoginVC: Bool?) -> Bool {
//    let model = UserModel.shared
//    if model.user_id == nil {
//        if isToLoginVC ?? false {
//            let vc = JFLoginViewController()
//            let nav = HJBaseNavigationController.init(rootViewController: vc)
//            nav.modalPresentationStyle = .fullScreen
//            hj_getCurrentViewController().present(nav, animated: true, completion: nil)
//        }
//        return false
//    }
//    return true
//}

// MARK: - 计算日期
/// 根据天数计算
func CPCurrentDateToWantDate(startDataString:String,day:Int)->String {
    /// 默认一周时间
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale.current
    dateFormatter.dateFormat = "MM.dd"

    let myDate = dateFormatter.date(from: startDataString)
    let newDate = myDate?.addingTimeInterval(Double(60 * 60 * 24 * day))

    return dateFormatter.string(from: newDate!)

}
/// 根据年数计算
func CPCurrentDateToWantDateByYMD(dateTime:Date?,year:Int?,month:Int?,day:Int?)->Date {
    let current = dateTime ?? Date()
    let calendar = Calendar(identifier: .gregorian)
    var comps:DateComponents?
    
    comps = calendar.dateComponents([.year,.month,.day], from: current)
    comps?.year = year ?? 0
    comps?.month = month ?? 0
    comps?.day = day ?? 0
    return calendar.date(byAdding: comps!, to: current) ?? Date()
}

func currentDateYearMonthDay(timeType:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale.current
    dateFormatter.dateFormat = timeType
    return dateFormatter.string(from: Date())
}


func callPhoneMethod(phoneNo: String) {
//    if userIsLogin(isToLoginVC: true) {
        let phone = "telprompt://" + phoneNo
        if UIApplication.shared.canOpenURL(URL(string: phone)!) {
            UIApplication.shared.openURL(URL(string: phone)!)
        }
        else {
            toast(text: "该设备不能拨打电话")
        }
//    }
}


func getTextSize(text:String, font: UIFont, size: CGSize) -> CGSize {
    let attributes = [NSAttributedString.Key.font: font]
    let option = NSStringDrawingOptions.usesLineFragmentOrigin
    let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
    return rect.size;
}

// MARK: - 正则 密码

func availablePassword(string: String) -> Bool {
    var result = false
    let regex  = "^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])).{8,16}$"
//    let pred   = NSPredicate(format: "SELF MATCHES \(regex)")
    let pred = NSPredicate.init(format: "SELF MATCHES %@", regex)
//    pred.predicateFormat = "SELF MATCHES \(regex)"
    result = pred.evaluate(with: string)
    return result
}

// 用户名（首字母为英文或下划线，6-30位字符）
func availableUsername(string: String) -> Bool {
    var result = false
    let regex  = "^[A-Za-z_][A-Za-z0-9]+$"
    let pred = NSPredicate.init(format: "SELF MATCHES %@", regex)
    result = pred.evaluate(with: string)
    return result
}

// MARK: - UIFont

func CPFont(font: CGFloat?) -> UIFont {
    return UIFont.systemFont(ofSize: font ?? 13.0)
}

func CPFont_Blod(font: CGFloat?) -> UIFont {
    return UIFont.boldSystemFont(ofSize: font ?? 13.0)
}





// MARK: - Data to json

func dataToJsonString(data: Data) -> String {
    
    if let  JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) {
        return JSONString
    }
    
    return ""
}

//func setupUserInfo(with dict: NSDictionary?) {
//    if let data = dict {
//        UserModel.shared.loadDataWithDic(data)
//        
//        var userInfo: [String: Any] = [:]
//        if let enterName = data.jf_string(forKey: UserModel.CodingKeys.enter_name.rawValue) {
//            userInfo["EnterName"] = enterName
//        }
//        
//        if let realName = data.jf_string(forKey: UserModel.CodingKeys.app_account.rawValue) {
//            userInfo["RealName"] = realName
//        }
//        
//        if let userName = data.jf_string(forKey: UserModel.CodingKeys.user_name.rawValue) {
//            userInfo["UserName"] = userName
//        }
//        
//        if let userType = data.jf_string(forKey: UserModel.CodingKeys.user_type.rawValue) {
//            userInfo["UserType"] = userType
//        }
//        
//        if let userID = data.jf_string(forKey: UserModel.CodingKeys.user_id.rawValue) {
//            userInfo["UserID"] = userID
//        }
//        
//        UserLogin.shared()?.skChangeUserInfo(userInfo)
//    }
//}


// MARK: - 彩色图片置灰，灰度图片
func grayImage(sourceImage : UIImage) -> UIImage {
    UIGraphicsBeginImageContext(sourceImage.size)
    let colorSpace = CGColorSpaceCreateDeviceGray()
    let context = CGContext(data: nil , width: Int(sourceImage.size.width), height: Int(sourceImage.size.height),bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)
    context?.draw(sourceImage.cgImage!, in: CGRect.init(x: 0, y: 0, width: sourceImage.size.width, height: sourceImage.size.height))
    let cgImage = context!.makeImage()
    let grayImage = UIImage.init(cgImage: cgImage!)
    return grayImage
}
